<template>
  <el-dialog
    v-model="dialogVisible"
    title="互评记录"
    width="60%"
    :before-close="handleClose"
  >
    <div class="peer-review-container">
      <el-table
        :data="peerReviews"
        style="width: 100%"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column prop="reviewer" label="评价人" width="180">
          <template #default="{ row }">
            <el-tag size="small">{{ row.reviewer }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="评分" width="120">
          <template #default="{ row }">
            <div class="score-display">
              <el-rate
                v-model="row.score"
                :max="5"
                disabled
                show-score
                text-color="#ff9900"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="feedback" label="评价内容">
          <template #default="{ row }">
            <div class="feedback-content">{{ row.feedback }}</div>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="peerReviews.length === 0 && !loading" class="no-data">
        暂无互评记录
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  submissionId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['update:visible'])

const dialogVisible = ref(props.visible)
const peerReviews = ref([])
const loading = ref(false)

watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal && props.submissionId) {
    fetchPeerReviews()
  }
})

watch(() => dialogVisible.value, (newVal) => {
  emit('update:visible', newVal)
})

const fetchPeerReviews = async () => {
  loading.value = true
  try {
    const response = await axios.get(`/backend/api/assignment/submission/${props.submissionId}/peer_reviews/`, {
      withCredentials: true
    })
    peerReviews.value = response.data
  } catch (error) {
    console.error('获取互评记录失败:', error)
    ElMessage.error('获取互评记录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.peer-review-container {
  padding: 20px 0;
}

.score-display {
  display: flex;
  align-items: center;
}

.feedback-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.no-data {
  text-align: center;
  color: #909399;
  padding: 20px;
}
</style>